// HotPostController.java
package com.scuec.groupfive.Controller;

import com.scuec.groupfive.entity.Post;
import com.scuec.groupfive.mapper.HotPostMapper;
import com.scuec.groupfive.service.HotPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@CrossOrigin
@RequestMapping("/hot-post")
public class HotPostController {

    @Autowired
    private HotPostService hotPostService;

    @Autowired
    private HotPostMapper hotPostMapper;

    @GetMapping("/list")
    public Map<String, Object> getHotPosts(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String timeRange) {

        Date startDate = null;
        Date endDate = new Date();

        // 时间范围计算
        if ("week".equals(timeRange)) {
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);
            cal.add(Calendar.DATE, -7);
            startDate = cal.getTime();
        } else if ("month".equals(timeRange)) {
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);
            cal.add(Calendar.MONTH, -1);
            startDate = cal.getTime();
        }

        List<Post> posts;
        int total;

        if (timeRange != null) {
            // 使用统一的热度排序查询
            int offset = (page - 1) * pageSize;
            posts = hotPostMapper.getHotPostsByTimeRange(timeRange, offset, pageSize);
            total = hotPostMapper.getHotPostsCountByTimeRange(timeRange);
        } else {
            // 全部数据也使用热度排序
            int offset = (page - 1) * pageSize;
            posts = hotPostMapper.getHotPostsWithPagination(offset, pageSize);
            total = hotPostMapper.getTotalHotPostsCount();
        }

        // 计算总页数
        int pages = (int) Math.ceil((double) total / pageSize);

        // 返回统一格式的响应
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("code", 200);
        result.put("message", "success");
        result.put("data", new HashMap<String, Object>() {{
            put("list", posts);
            put("total", total);
            put("pageNum", page);
            put("pageSize", pageSize);
            put("pages", pages);
        }});

        return result;
    }

    @GetMapping("/list-by-date")
    public Map<String, Object> getHotPostsByDateRange(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize) {
        endDate = new Date(endDate.getTime() + 24 * 60 * 60 * 1000 - 1);
        List<Post> posts = hotPostService.getHotPostsByDateRange(startDate, endDate, page, pageSize);
        int total = hotPostMapper.getHotPostsCountByDateRange(startDate, endDate);

        Map<String, Object> result = new HashMap<>();
        result.put("list", posts);
        result.put("total", total);
        result.put("currentPage", page);
        result.put("pageSize", pageSize);
        return result;
    }

    @GetMapping("/score/{postId}")
    public Map<String, Object> getHotScore(@PathVariable Long postId) {
        Post post = hotPostMapper.getPostById(postId);
        if (post == null) {
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("error", "Post not found");
            return errorMap;
        }

        double score = hotPostService.calculateHotScore(postId);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("postId", postId);
        resultMap.put("userId", post.getUserId());
        resultMap.put("hotScore", score);
        resultMap.put("viewCount", hotPostMapper.getViewCountByPostId(postId));
        resultMap.put("commentCount", hotPostMapper.getCommentCountByPostIdAndUser(postId, post.getUserId()));
        resultMap.put("likeCount", hotPostMapper.getLikeCountByPostIdAndUser(postId, post.getUserId()));
        resultMap.put("favoriteCount", hotPostMapper.getFavoriteCountByPostIdAndUser(postId, post.getUserId()));
        resultMap.put("type", post.getTag()); // 添加类型字段
        resultMap.put("createdAt", post.getCreatedAt()); // 添加创建时间字段

        return resultMap;
    }

    @GetMapping("/user-interaction/{postId}/{userId}")
    public Map<String, Object> getUserInteractionData(
            @PathVariable Long postId,
            @PathVariable Long userId) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("postId", postId);
        resultMap.put("userId", userId);
        resultMap.put("commentCount", hotPostMapper.getCommentCountByPostIdAndUser(postId, userId));
        resultMap.put("likeCount", hotPostMapper.getLikeCountByPostIdAndUser(postId, userId));
        resultMap.put("favoriteCount", hotPostMapper.getFavoriteCountByPostIdAndUser(postId, userId));

        return resultMap;
    }
}